package com.haredot.controller;

import com.haredot.entity.ResourceType;
import com.haredot.service.ResourceTypeService;
import com.haredot.validation.Insert;
import com.haredot.validation.Update;
import com.haredot.vo.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/rtype")
public class ResourceTypeController {

    @Resource
    private ResourceTypeService resourceTypeService ;

    @PostMapping
    @PreAuthorize("hasAnyAuthority('rtype:add', 'rtype:add:child')")
    public R<?> addResourceType(@RequestBody @Validated(value = Insert.class) ResourceType resourceType) {
        return resourceTypeService.saveResourceType(resourceType) ;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('rtype:remove')")
    public R<?> removeResourceType(@PathVariable("id") Long id) {
        return resourceTypeService.removeResourceType(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    @PreAuthorize("hasAuthority('rtype:batch:remove')")
    public R<?> removeBatchResourceType(@RequestBody List<Long> ids) {
        return resourceTypeService.removeBatchByIds(ids) ? R.ok().build() : R.fail().build() ;
    }

    /**
     * 修改资源类型信息
     * @param id
     * @param resourceType
     * @return
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('rtype:modify')")
    public R<?> modifyResourceType(@PathVariable("id") Long id, @RequestBody @Validated(Update.class) ResourceType resourceType) {

        Assert.isTrue(Objects.equals(id, resourceType.getId()) , "资源类型ID有误");
        return resourceTypeService.modifyResourceType(resourceType) ;
    }

    /**
     * 查询所有资源类型
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('rtype')")
    public R<ResourceType> list() {
        List<ResourceType> list = resourceTypeService.list();
        return R.<ResourceType>ok().data(list);
    }

}
